package com.example.first.thread;

import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;

/**
 * @Author LSQ
 * @Description TODO
 * @date 2021/9/23 22:48
 * @Version 1.0
 */


class Demo {
    int i = 0;

    public synchronized void doSth() {
        System.out.println(Thread.currentThread().getName() + " do it, result: " + i);
        i++;
    }

    public void doSth1() {
        synchronized (LearnSynchronized4.class) {
            System.out.println("Hello world!");
        }
    }

}

class Handler implements Runnable {
    private String name;
    private Demo demo;

    public Handler(String name, Demo demo) {
        this.demo = demo;
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(name + " start! Time@" + new Date());
        deil(demo);
        processCommand();
        ret(this.demo);
        System.out.println(name + " end! Time@" + new Date());

    }

    public void deil(Demo demo) {
        demo.doSth();
    }

    public Demo ret(Demo demo) {
        return this.demo;
    }

    private void processCommand() {
        Random random = new Random();
        try {
            Thread.sleep((random.nextInt(10) + 1) * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return this.name;
    }


}


public class LearnSynchronized4 {

    /**
     * 1、锁的升级过程：偏向锁 ->  轻量级锁 -> 重量级锁
     * 2、锁的粗化： 提升性能
     * 3、锁的消除
     * <p>
     * 每个线程都有自己的线程栈 线程栈的栈针，每开一个方法，都有一个栈针  不能被其它线程访问
     */


    private static final int CORE_POOL_SIZE = 30;
    private static final int MAX_POOL_SIZE = 50;
    private static final int QUEUE_CAPACITY = 100000;
    private static final int TASK_COUNT = 20000;


    public static void main(String[] args) {
        LearnSynchronized4 learnSynchronized = new LearnSynchronized4();

        ExecutorService executorService = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
                0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(QUEUE_CAPACITY));

        Demo demo = new Demo();

        for (int i = 0; i < TASK_COUNT; i++) {
            Handler handle = new Handler("Task " + String.valueOf(i), demo);
            executorService.execute(handle);
        }

        executorService.shutdown();
    }
}
